'use strict';
/**
 * Created by henian.xu on 2018/11/5.
 *
 */

module.exports = function(options, app) {
  return async (ctx, next) => {
    await next();
    // ignore status if not 404
    // 这里的路由是前端的 所以 404 都返回走前端路由
    // console.log(ctx.status, ctx.method, ctx.path);
    if (ctx.status !== 404 || ctx.method !== 'GET') {
      return;
    }

    ctx.status = 200;
    const path = ctx.path;
    if (/\.js$/.test(path)) {
      ctx.set('Content-Type', 'application/javascript');
    }
    if (/\.css/.test(path)) {
      ctx.set('Content-Type', 'text/css');
    }
    // webpack hot reload
    // egg will set 'content-length' with value, it will disable the hot middleware keep alive.
    // egg 默认设置了 'content-length' 值，导致热更新失败，建议去掉该值保持活跃
    if (ctx.path === '/__webpack_hmr') {
      ctx.response.remove('content-length');
    }
    // the "nuxt.render" returns callback, not Promise
    return await new Promise((resolve, reject) => {
      ctx.res.on('close', resolve);
      ctx.res.on('finish', resolve);
      app.nuxt.render(ctx.req, ctx.res, promise => {
        // nuxt.render passes a rejected promise into callback on error.
        promise.then(resolve).catch(reject);
      });
    });
  };
};
